<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="数据结构和算法"><meta name="keywords" content="算法"><meta name="author" content="晟松"><meta name="copyright" content="晟松"><title>数据结构和算法 | 晟松</title><link rel="shortcut icon" href="/logo.png"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?c34d81d53341febe06a155941e2df16d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E7%AE%97%E6%B3%95%E5%A4%8D%E6%9D%82%E5%BA%A6%E5%88%86%E6%9E%90"><span class="toc-number">1.</span> <span class="toc-text">1.算法复杂度分析</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6"><span class="toc-number">1.1.</span> <span class="toc-text">1.时间复杂度</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E7%A9%BA%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6"><span class="toc-number">1.2.</span> <span class="toc-text">2.空间复杂度</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="toc-number">2.</span> <span class="toc-text">2.数据结构</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-KPM%E7%AE%97%E6%B3%95%E5%92%8Cnext%E6%95%B0%E7%BB%84%E6%B1%82%E5%80%BC"><span class="toc-number">2.1.</span> <span class="toc-text">1.KPM算法和next数组求值</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E6%A0%91"><span class="toc-number">2.2.</span> <span class="toc-text">2.树</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E5%9B%BE"><span class="toc-number">2.3.</span> <span class="toc-text">3.图</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#4-%E6%9F%A5%E6%89%BE"><span class="toc-number">2.4.</span> <span class="toc-text">4.查找</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#5-%E6%8E%92%E5%BA%8F"><span class="toc-number">2.5.</span> <span class="toc-text">5.排序</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%AE%97%E6%B3%95%E6%80%9D%E6%83%B3"><span class="toc-number">3.</span> <span class="toc-text">3.计算机算法思想</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E9%80%92%E5%BD%92%E4%B8%8E%E5%88%86%E6%B2%BB"><span class="toc-number">3.1.</span> <span class="toc-text">1.递归与分治</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92"><span class="toc-number">3.2.</span> <span class="toc-text">2.动态规划</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95"><span class="toc-number">3.3.</span> <span class="toc-text">3.贪心算法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#4-%E5%9B%9E%E6%BA%AF%E6%B3%95"><span class="toc-number">3.4.</span> <span class="toc-text">4.回溯法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#5-%E5%88%86%E6%94%AF%E9%99%90%E7%95%8C%E6%B3%95"><span class="toc-number">3.5.</span> <span class="toc-text">5.分支限界法</span></a></li></ol></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">晟松</div><div class="author-info__description text-center">晟松的博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://gitee.com/cheng_song">Gitee</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">52</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">45</span></a></div></div></div><div id="content-outer"><div id="top-container" style="background-image: url(/img/blog-bg.jpg)"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">晟松</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">数据结构和算法</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-09-17</time><div class="post-meta-wordcount"><span>字数总计: </span><span class="word-count">6.7k</span><span class="post-meta__separator">|</span><span>阅读时长: 24 分钟</span></div></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>虽然之前上了一些关于数据结构、算法之类的课，但之前都没有怎么搞懂，尤其是算法里面的一些算法思想，现在看能不能补上，就是一些大佬的算法指导，刷LeetCode的一些题，回看之前的书上面的重点。</p>
<p>教材是清华大学出版社的数据结构(C语言版)、计算机算法分析与设计(第四版)</p>
<h4 id="1-算法复杂度分析"><a href="#1-算法复杂度分析" class="headerlink" title="1.算法复杂度分析"></a>1.算法复杂度分析</h4><h5 id="1-时间复杂度"><a href="#1-时间复杂度" class="headerlink" title="1.时间复杂度"></a>1.时间复杂度</h5><p><strong>大 O 时间复杂度表示法</strong>( T(n) =O(f(n)) ） 实际上并不具体表示代码真正的执行时间，而是表示 <strong>代码执行时间随数据规模增长的变化趋势</strong>，所以也叫 <strong>渐进时间复杂度</strong>，简称 <strong>时间复杂度</strong></p>
<p>由于 <strong>时间复杂度</strong> 描述的是算法执行时间与数据规模的 <strong>增长变化趋势</strong>，所以 <strong>常量、低阶、系数</strong> 实际上对这种增长趋势不产生决定性影响，所以在做时间复杂度分析时 <strong>忽略</strong> 这些项</p>
<p>例：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">cal</span>(<span class="params">m, n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> sum_3 = <span class="number">0</span>;</span><br><span class="line">   <span class="keyword">let</span> i = <span class="number">1</span>;</span><br><span class="line">   <span class="keyword">let</span> j = <span class="number">1</span>;</span><br><span class="line">   <span class="keyword">for</span> (; i &lt;= m; ++i) &#123;</span><br><span class="line">     j = <span class="number">1</span>; </span><br><span class="line">     <span class="keyword">for</span> (; j &lt;= n; ++j) &#123;</span><br><span class="line">       sum_3 = sum_3 +  i * j;</span><br><span class="line">     &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以上代码也是求和，两层 for 循环 ，求 sum_3 的数据规模为 m 和 n，所以时间复杂度为 O(m*n)。</p>
<p>时间复杂度可以分为：</p>
<ul>
<li><strong>最好情况时间复杂度</strong>（best case time complexity）：在最理想的情况下，执行这段代码的时间复杂度。</li>
<li><strong>最坏情况时间复杂度</strong>（worst case time complexity）：在最糟糕的情况下，执行这段代码的时间复杂度。</li>
<li><strong>平均情况时间复杂度</strong>（average case time complexity），用代码在所有情况下执行的次数的加权平均值表示。也叫 <strong>加权平均时间复杂度</strong> 或者 <strong>期望时间复杂度</strong>。</li>
<li><strong>均摊时间复杂度</strong>（amortized time complexity）: 在代码执行的所有复杂度情况中绝大部分是低级别的复杂度，个别情况是高级别复杂度且发生具有时序关系时，可以将个别高级别复杂度均摊到低级别复杂度上。基本上均摊结果就等于低级别复杂度</li>
</ul>
<p>一般我们最关心的还是<strong>最坏情况</strong>下的时间复杂度或<strong>平均</strong>复杂度</p>
<p><strong>O(1) &lt; O(logn) &lt; (n) &lt; O(nlogn) &lt; O(n2) &lt; O(n3) &lt; O(2n) &lt; O(n!) &lt; O(nn)</strong></p>
<h5 id="2-空间复杂度"><a href="#2-空间复杂度" class="headerlink" title="2.空间复杂度"></a>2.空间复杂度</h5><p>类比一下，空间复杂度全称就是 <strong>渐进空间复杂度</strong>（asymptotic space complexity），表示 <strong>算法的存储空间与数据规模之间的增长关系</strong></p>
<p>例：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">print</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line"> <span class="keyword">const</span> newArr = []; <span class="comment">// 第 2 行</span></span><br><span class="line"> newArr.length = n; <span class="comment">// 第 3 行</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt;n; ++i) &#123;</span><br><span class="line">    newArr[i] = i * i;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> j = n-<span class="number">1</span>; j &gt;= <span class="number">0</span>; --j) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(newArr[i])</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>跟时间复杂度分析一样，我们可以看到，第 2 行代码中，我们申请了一个空间存储变量 newArr ，是个空数组。第 3 行把 newArr 的长度修改为 n 的长度的数组，每项的值为 undefined ，除此之外，剩下的代码都没有占用更多的空间，所以整段代码的空间复杂度就是 O(n)。</p>
<hr>
<h4 id="2-数据结构"><a href="#2-数据结构" class="headerlink" title="2.数据结构"></a>2.数据结构</h4><h5 id="1-KPM算法和next数组求值"><a href="#1-KPM算法和next数组求值" class="headerlink" title="1.KPM算法和next数组求值"></a>1.KPM算法和next数组求值</h5><p>这是一个进行字符串匹配的算法，原理是求一个字符串的某一个字符的前面的字符串最大相等的前缀和后缀</p>
<p>kmp算法为</p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">kmp</span><span class="params">(<span class="built_in">string</span> s,<span class="built_in">string</span> t,<span class="keyword">int</span> pos)</span></span>&#123;<span class="comment">//s为主串，t为模式串</span></span><br><span class="line">	i = pos;</span><br><span class="line">	j=<span class="number">1</span>;</span><br><span class="line">	<span class="keyword">while</span>(i&lt;s[<span class="number">0</span>] &amp;&amp; j&lt;t[<span class="number">0</span>])&#123;<span class="comment">//这两个0的位置存储的是string的长度</span></span><br><span class="line">		<span class="keyword">if</span>(j==<span class="number">0</span> || s[i] == t[j])	&#123;++i;++j&#125;<span class="comment">//j=0表示主串第i个字符和模式串第1个字符不匹配，需从第i+1个字符从新匹配</span></span><br><span class="line">		<span class="keyword">else</span>	j = next[j];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span>(j&gt;t[<span class="number">0</span>]) <span class="keyword">return</span> i-t[<span class="number">0</span>]; <span class="comment">// 匹配成功</span></span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>求next数组的算法是仿照kmp的算法来的，<strong>i</strong>不进行后退，只有模式串滑动。<strong>因为求next也就是主串和模式串都是自己</strong>，可进行模仿kmp</p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">get_next</span><span class="params">(<span class="built_in">string</span> t,<span class="keyword">int</span> next[])</span></span>&#123;</span><br><span class="line">	i=<span class="number">1</span>; j=<span class="number">0</span>; next[<span class="number">1</span>]=<span class="number">0</span>;</span><br><span class="line">	<span class="keyword">while</span>(i&lt;t[<span class="number">0</span>])&#123;</span><br><span class="line">	<span class="keyword">if</span>(j==<span class="number">0</span> || t[i] == t[j])&#123;++i;++j;next[i]=j&#125;	</span><br><span class="line">	<span class="keyword">else</span>	j = next[j];</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>核心就是next[i]=j，先进行++是因为前面相等，则后面一个字符的next就是在if里相等的最后一个字符<strong>j</strong>的后面一个字符。符合前缀等于后缀的原则。</p>
<p>改进后的next算法</p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">get_nextval</span><span class="params">(<span class="built_in">string</span> t,<span class="keyword">int</span> nextval[])</span></span>&#123;</span><br><span class="line">	i=<span class="number">1</span>; j=<span class="number">0</span>; nextval[<span class="number">1</span>]=<span class="number">0</span>;</span><br><span class="line">	<span class="keyword">while</span>(i&lt;t[<span class="number">0</span>])&#123;</span><br><span class="line">	<span class="keyword">if</span>(j=<span class="number">0</span> || t[i] == t[j])&#123;</span><br><span class="line">		++i;j++;</span><br><span class="line">		<span class="keyword">if</span>(t[i] != t[j])	nextval[i]=j;</span><br><span class="line">		<span class="keyword">else</span>	nextval[i] = nextval[j];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> j = nextval[j];</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="2-树"><a href="#2-树" class="headerlink" title="2.树"></a>2.树</h5><p>一般研究<strong>二叉树</strong></p>
<p>1.第i层至多有2^(i-1)个节点</p>
<p>2.深度为k的二叉树至多有2^k-1个节点</p>
<p>3.任何一颗二叉树t，若其叶子节点数为N0，度为2的节点数为N2，则N0=N2+1</p>
<p>​    对于完全二叉树，就是对每一个节点，若有右孩子，则必有左孩子，且右分支的子孙的最大层次为l，则其左分支下的子孙的最大层次必为l或l+1.就是节点从左到右排顺序，这个顺序不能断。</p>
<p>4.有n个节点的完全二叉树的深度为<strong>log2 n向下取整+1</strong></p>
<p>5.对任意节点i，若2i&gt;n，则节点i无左孩子；如果有左孩子，其左孩子必是节点2i</p>
<p>6.若2i+1&gt;n，则节点i无右孩子；如果有右孩子，其右孩子必是节点2i+1</p>
<p>7.i=1，则为根节点，若i&gt;1，则双亲节点为i/2向下取余</p>
<p>二叉树可使用二叉链表进行存储，例如<code>lchild | data | rchild</code>。</p>
<p><strong>遍历</strong></p>
<p>先序，中序，后序。为根节点在查序中的位置</p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="comment">//先序的递归算法</span></span><br><span class="line"><span class="function">Status <span class="title">preorderTraverse</span><span class="params">(Bitree t,Status(* visit)(TElemType e))</span></span>&#123;</span><br><span class="line">    <span class="function">status <span class="title">printelement</span><span class="params">(telemType e)</span></span>&#123;</span><br><span class="line">        <span class="built_in">printf</span>(e);	<span class="comment">//打印输出节点,	调用实例preorderTraverse(t,printelement);</span></span><br><span class="line">        <span class="keyword">return</span> ok;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(t)&#123;</span><br><span class="line">        <span class="keyword">if</span>(visit(t-&gt;data))</span><br><span class="line">            <span class="keyword">if</span>(preorderTraverse(t-&gt;lchild,visit))</span><br><span class="line">                <span class="keyword">if</span>(preorderTraverse(t-&gt;rchild,visit)) <span class="keyword">return</span> ok;</span><br><span class="line">        <span class="keyword">return</span> error;</span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">return</span> ok;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//二叉树数据结构 js语法</span></span><br><span class="line"><span class="function">function <span class="title">TreeNode</span><span class="params">(val)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.val = val;</span><br><span class="line">      <span class="keyword">this</span>.left = <span class="keyword">this</span>.right = null;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">function <span class="title">DFStraval</span><span class="params">(node)</span></span>&#123;  </span><br><span class="line">        <span class="keyword">if</span>(!node) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">            console.<span class="built_in">log</span>(node.val);</span><br><span class="line">            traval(node.left);</span><br><span class="line">            traval(node.right);</span><br><span class="line">        </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">function <span class="title">BFStraval</span><span class="params">(node)</span></span>&#123; </span><br><span class="line">    <span class="keyword">const</span> <span class="built_in">queue</span> = [root];</span><br><span class="line">    <span class="keyword">while</span>(<span class="built_in">queue</span>.length)&#123;</span><br><span class="line">        let len  = <span class="built_in">queue</span>.length;</span><br><span class="line">        <span class="keyword">while</span>(len)&#123;</span><br><span class="line">            let node = <span class="built_in">queue</span>.shift();</span><br><span class="line">            console.<span class="built_in">log</span>(node.val);</span><br><span class="line">            node.left&amp;&amp;<span class="built_in">queue</span>.push(node.left);</span><br><span class="line">            node.right&amp;&amp;<span class="built_in">queue</span>.push(node.right);</span><br><span class="line">            len--;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="3-图"><a href="#3-图" class="headerlink" title="3.图"></a>3.图</h5><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/czsupercar/article/details/88735143">图的邻接表存储</a></p>
<p><strong>图的遍历</strong></p>
<p>深度优先，广度优先</p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="comment">//深度优先遍历</span></span><br><span class="line">Boolean visited[MAX]; <span class="comment">//访问标志数组，初始值为false，当此节点被访问了，对应的visited[i]变为true</span></span><br><span class="line">Status(*Visitedfunc)(<span class="keyword">int</span> v)); <span class="comment">//函数变量</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">DFSTraverse</span><span class="params">(Graph G,Status(*visit)(<span class="keyword">int</span> v))</span></span>&#123;</span><br><span class="line">    VisitedFunc = Visit;</span><br><span class="line">    <span class="keyword">for</span>(v=<span class="number">0</span>;v&lt;G.vexnum;v++)&#123;visited[v] = <span class="literal">false</span>&#125;	<span class="comment">//初始化</span></span><br><span class="line">    <span class="keyword">for</span>(v=<span class="number">0</span>;v&lt;G.vexnum;v++)&#123;</span><br><span class="line">        <span class="keyword">if</span>(!visited[v]) DFS(G,v); <span class="comment">//对未访问过的节点调用DFS</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">DFS(Graph G,<span class="keyword">int</span> v)&#123;</span><br><span class="line">    visited[v] = <span class="literal">true</span>;	VisitFunc(v);	<span class="comment">//输出v节点</span></span><br><span class="line">    <span class="comment">//FirstAdjVex返回v的第一个邻接节点，NextAdjVex返回v的相对于w的下一个节点，若w是v的最后一个节点，返回空</span></span><br><span class="line">    <span class="keyword">for</span>(w=FirstAdjVex(G,v);w&gt;<span class="number">0</span>;w=NextAdjVex(G,v,w))&#123;</span><br><span class="line">        <span class="keyword">if</span>(!visted[w])	DFS(G,w);	<span class="comment">//对v的未访问过的邻接节点w递归调用DFS</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>最小生成树</strong></p>
<p>稀疏图用Kruskal，稠密图用Prim</p>
<p>n个节点至少需要n-1条边连通，但边上还有权值，选择权值之和最小的n-1条边，可能不唯一</p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="comment">//最小生成树，普里姆算法，最小生成树不断壮大的过程，选顶点.使用邻接矩阵存储的网</span></span><br><span class="line"><span class="comment">//不断寻找与逐渐生成的最小生成树相连的边权最小的点加入</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">MiniSpanTree_prim</span><span class="params">(MGraph G ,vertexType u)</span></span>&#123;</span><br><span class="line">    <span class="comment">//从第u个顶点出发构造最小生成树</span></span><br><span class="line">    <span class="comment">//closedge记录从顶点集U到V-U的代价最小的边的辅助数组定义。就是未加入的节点和这棵生成树之间的权值</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> &#123;</span></span><br><span class="line">        VertexType adjvex;<span class="comment">//存储该边依附在顶点集U中的顶点</span></span><br><span class="line">        VRtype lowcost;<span class="comment">//存储在该边上的权值</span></span><br><span class="line">    &#125;closedge[MAX_VERTEX_NUM]</span><br><span class="line">        k = LocateVex(G,u);	<span class="comment">//开始的顶点的位置</span></span><br><span class="line">    <span class="keyword">for</span>(j=<span class="number">0</span>;j&lt;G.vexnum;j++)&#123;	<span class="comment">//辅助数组初始化,lowcost为开始节点u与其他节点之间的权值，权值可为无穷大</span></span><br><span class="line">        <span class="keyword">if</span>(j != k) closedge[j] = &#123;u,G.arc[k][j].adj&#125; <span class="comment">//&#123;adjvex,lowcost&#125;</span></span><br><span class="line">    &#125;</span><br><span class="line">    closedge[k].lowcost = <span class="number">0</span>;	<span class="comment">//初始U=&#123;u&#125;</span></span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">1</span>;i&lt;G.vexnum;i++)&#123;	<span class="comment">//选择剩下的G.vexnum-1个顶点</span></span><br><span class="line">        k=minimum(closedge)；	<span class="comment">//选择一个在closedge里边权值最小的顶点的序号，将其顶点和边加入最小生成树        </span></span><br><span class="line">        <span class="built_in">printf</span>(closedge[k].adjvex,G.vexs[k]);	<span class="comment">//输出边</span></span><br><span class="line">        closedge[k].lowcost = <span class="number">0</span>;	<span class="comment">//第K顶点并入U集</span></span><br><span class="line">        <span class="keyword">for</span>(j=<span class="number">0</span>;j&lt;G.vexnum;j++)&#123;</span><br><span class="line">            <span class="comment">//新顶点并入U后，重新选择最小边。就是更新closedge里面的lowcost的值</span></span><br><span class="line">            <span class="keyword">if</span>(G.arcs[k][j].adj&lt;closedge[j].lowcost)	</span><br><span class="line">                <span class="comment">//权值比原有的lowcost小，更新。	注意是k节点和其他节点之间的权值与之前节点的权值进行比较</span></span><br><span class="line">                closedge[j] = &#123;G.vexs[k],G.arcs[k][j].adj&#125;;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>另一个就是Kruskal算法，即连通分量（即不能形成环）不断合并的过程。在开始就将n个顶点加入U，选边。</p>
<p>每次选择边权最小的边链接两个端点是kruskal的规则，并实时判断两个点之间有没有间接联通形成环。</p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/mgsky1/article/details/77840286">参考链接</a></p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">int</span> n,m,tot=<span class="number">0</span>,k=<span class="number">0</span>;<span class="comment">//n端点总数，m边数，tot记录最终答案，k已经连接了多少边 </span></span><br><span class="line"><span class="keyword">int</span> fat[<span class="number">200</span>];<span class="comment">//记录集体老大。</span></span><br><span class="line"><span class="comment">//并查集就是一个用双亲表示法所表示的森林，我们可以利用这个结构来查找某一个顶点的双亲，进而找到根结点。这样，我们就能判断某两个顶点是否同源，在图中的表现就是加上这条边后会不会形成环。并查集以顶点为基准，有几个顶点，就有几项。</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">node</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">	<span class="keyword">int</span> from,to,dis;<span class="comment">//结构体储存边,dis为权值 </span></span><br><span class="line">&#125;edge[<span class="number">2000</span>];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">cmp</span><span class="params">(<span class="keyword">const</span> node &amp;a,<span class="keyword">const</span> node &amp;b)</span><span class="comment">//sort排序（当然你也可以快排） </span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">return</span> a.dis&lt;b.dis;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">father</span><span class="params">(<span class="keyword">int</span> x)</span><span class="comment">//找集体老大，并查集的一部分，就是寻找这个顶点的根 </span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(fat[x]!=x)	<span class="comment">//如果这不是根，就继续向上查找，直至找到根</span></span><br><span class="line">	<span class="keyword">return</span> father(fat[x]);</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">return</span> x;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">unionn</span><span class="params">(<span class="keyword">int</span> x,<span class="keyword">int</span> y)</span><span class="comment">//加入团体，并查集的一部分 </span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">//fat[father(x)]=father(y);	//这感觉有些不能理解，甚至fat[x]=y好像也行</span></span><br><span class="line">    fat[x]=father(y);	<span class="comment">//这样也行</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">scanf</span>(<span class="string">&quot;%d%d&quot;</span>,&amp;n,&amp;m);<span class="comment">//输入点数，边数 </span></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=m;i++)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">scanf</span>(<span class="string">&quot;%d%d%d&quot;</span>,&amp;edge[i].from,&amp;edge[i].to,&amp;edge[i].dis);<span class="comment">//输入边的信息 </span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=n;i++) fat[i]=i;<span class="comment">//自己最开始就是自己的老大（初始化），自己的根就是自己</span></span><br><span class="line">	sort(edge+<span class="number">1</span>,edge+<span class="number">1</span>+m,cmp);<span class="comment">//按权值排序（kruskal的体现） </span></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=m;i++)<span class="comment">//从小到大遍历 </span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span>(k==n<span class="number">-1</span>) <span class="keyword">break</span>;<span class="comment">//n个点需要n-1条边连接 </span></span><br><span class="line">		<span class="keyword">if</span>(father(edge[i].from)!=father(edge[i].to))<span class="comment">//假如不在一个团体，其根不一样，就是判断形不形成环 </span></span><br><span class="line">		&#123;</span><br><span class="line">			unionn(edge[i].from,edge[i].to);<span class="comment">//加入这个根的团体 </span></span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">&quot;from=%d to=%d \n&quot;</span>,edge[i].from,edge[i].to);<span class="comment">//打印加入的边的路径</span></span><br><span class="line">			tot+=edge[i].dis;<span class="comment">//记录边权 </span></span><br><span class="line">			k++;<span class="comment">//已连接边数+1 </span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;%d&quot;</span>,tot);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//测试用例</span></span><br><span class="line"><span class="comment">//6 7						</span></span><br><span class="line"><span class="comment">//0 2 1</span></span><br><span class="line"><span class="comment">//2 5 4</span></span><br><span class="line"><span class="comment">//5 3 2</span></span><br><span class="line"><span class="comment">//2 1 5</span></span><br><span class="line"><span class="comment">//1 4 3</span></span><br><span class="line"><span class="comment">//4 5 6</span></span><br><span class="line"><span class="comment">//0 4 3</span></span><br></pre></td></tr></table></figure>

<hr>
<p><strong>拓扑排序</strong></p>
<p>在有向图中选一个没有前驱的顶点（<strong>入度为0</strong>）输出，在图中删除该顶点和所有<strong>以它为尾的弧（也就是边）</strong></p>
<p>可通过拓扑排序判断网中是否存在环，<strong>若所有的顶点都在拓扑排序序列中，则不存在环</strong>。</p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="comment">//拓扑排序，判断是否有环</span></span><br><span class="line"><span class="function">Status <span class="title">topologicalSort</span><span class="params">(AlGraph G)</span></span>&#123;</span><br><span class="line">    findinDegree(G,indegree);	<span class="comment">//对各个顶点求入度 indegree[0……vexnum-1]</span></span><br><span class="line">    InitStack(S);</span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">0</span>;i&lt;G.vexnum;++i)&#123;</span><br><span class="line">        <span class="keyword">if</span>(!indegree[i]) Push(S,i);	`<span class="comment">//入度为0的顶点入栈</span></span><br><span class="line">    &#125;</span><br><span class="line">    count = <span class="number">0</span>;	<span class="comment">//对输出顶点计数</span></span><br><span class="line">    <span class="keyword">while</span>(!StackEmpty(S))&#123;</span><br><span class="line">        Pop(S,i);</span><br><span class="line">        <span class="built_in">printf</span>(i,G.vertices[i].data);	++count;	<span class="comment">//输出i号顶点</span></span><br><span class="line">        <span class="keyword">for</span>(p=G.vertices[i].firstarc; p;p=p-&gt;nextarc)&#123;	<span class="comment">//判断这个输出顶点的邻接点</span></span><br><span class="line">            k = p-&gt;adjvex;	<span class="comment">//对i号顶点的每个邻接点的入度-1</span></span><br><span class="line">            <span class="keyword">if</span>(!(--indegree[k]))	Push(S,k);	<span class="comment">//若入度为0，则入栈</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(count&lt;G.vexnum)	<span class="keyword">return</span> error;	<span class="comment">//该有向图有回路</span></span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">return</span> Ok;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<hr>
<p><strong>单源最短路径</strong></p>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/RioTian/p/12597634.html">参考此链接</a></p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 单源最短路径：Dijkstra 算法 </span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span>  matrix[<span class="number">100</span>][<span class="number">100</span>]; <span class="comment">// 邻接矩阵</span></span><br><span class="line"><span class="keyword">bool</span> visited[<span class="number">100</span>];     <span class="comment">// 标记数组</span></span><br><span class="line"><span class="keyword">int</span>  dist[<span class="number">100</span>];        <span class="comment">// 源点到顶点 i 的最短距离</span></span><br><span class="line"><span class="keyword">int</span>  path[<span class="number">100</span>];        <span class="comment">// 记录最短路的路径</span></span><br><span class="line"><span class="keyword">int</span>  source;           <span class="comment">// 源点</span></span><br><span class="line"><span class="keyword">int</span>  vertex_num;       <span class="comment">// 顶点数</span></span><br><span class="line"><span class="keyword">int</span>  edge_num;         <span class="comment">// 边数</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Dijkstra</span><span class="params">(<span class="keyword">int</span> source)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">memset</span>(visited, <span class="number">0</span>, <span class="keyword">sizeof</span>(visited));  <span class="comment">// 初始化标记数组</span></span><br><span class="line">    visited[source] = <span class="literal">true</span>;	<span class="comment">//开始节点被访问</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex_num; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        dist[i] = matrix[source][i];	<span class="comment">//开始节点到其他节点之间的权值</span></span><br><span class="line">        path[i] = source;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> min_cost;        <span class="comment">// 权值最小</span></span><br><span class="line">    <span class="keyword">int</span> min_cost_index;  <span class="comment">// 权值最小的下标</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; vertex_num; i++)  <span class="comment">// 找到源点到另外 vertex_num-1 个点的最短路径</span></span><br><span class="line">    &#123;</span><br><span class="line">        min_cost = INT_MAX;	<span class="comment">//先设为最大值</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; vertex_num; j++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span> (visited[j] == <span class="literal">false</span> &amp;&amp; dist[j] &lt; min_cost)  <span class="comment">// 先找到与之相连的权值最小的节点</span></span><br><span class="line">            &#123;</span><br><span class="line">                min_cost = dist[j];</span><br><span class="line">                min_cost_index = j;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        visited[min_cost_index] = <span class="literal">true</span>;  <span class="comment">// 该点已找到，进行标记</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; vertex_num; j++)  <span class="comment">// 更新 dist 数组</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span> (visited[j] == <span class="literal">false</span> &amp;&amp;	<span class="comment">//表示这个节点还未被访问</span></span><br><span class="line">                matrix[min_cost_index][j] != INT_MAX &amp;&amp;  <span class="comment">// 确保两点之间有边</span></span><br><span class="line">                matrix[min_cost_index][j] + min_cost &lt; dist[j])	<span class="comment">//**算法核心</span></span><br><span class="line">            &#123;</span><br><span class="line">                dist[j] = matrix[min_cost_index][j] + min_cost;</span><br><span class="line">                path[j] = min_cost_index;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;请输入图的顶点数（&lt;100）：&quot;</span>;</span><br><span class="line">    <span class="built_in">cin</span> &gt;&gt; vertex_num;</span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;请输入图的边数：&quot;</span>;</span><br><span class="line">    <span class="built_in">cin</span> &gt;&gt; edge_num;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex_num; i++)</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; vertex_num; j++)</span><br><span class="line">            matrix[i][j] = (i != j) ? INT_MAX : <span class="number">0</span>;  <span class="comment">// 初始化 matrix 数组</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;请输入边的信息：\n&quot;</span>;</span><br><span class="line">    <span class="keyword">int</span> u, v, w;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; edge_num; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">cin</span> &gt;&gt; u &gt;&gt; v &gt;&gt; w;</span><br><span class="line">        matrix[u][v] = matrix[v][u] = w;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;请输入源点（&lt;&quot;</span> &lt;&lt; vertex_num &lt;&lt; <span class="string">&quot;）：&quot;</span>;</span><br><span class="line">    <span class="built_in">cin</span> &gt;&gt; source;</span><br><span class="line">    Dijkstra(source);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex_num; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (i != source)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">cout</span> &lt;&lt; source &lt;&lt; <span class="string">&quot; 到 &quot;</span> &lt;&lt; i &lt;&lt; <span class="string">&quot; 的最短距离是：&quot;</span> &lt;&lt; dist[i] &lt;&lt; <span class="string">&quot;，路径是：&quot;</span> &lt;&lt; i;</span><br><span class="line">            <span class="keyword">int</span> t = path[i];</span><br><span class="line">            <span class="keyword">while</span> (t != source)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;--&quot;</span> &lt;&lt; t;</span><br><span class="line">                t = path[t];</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;--&quot;</span> &lt;&lt; source &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//结果</span></span><br></pre></td></tr></table></figure>

<hr>
<h5 id="4-查找"><a href="#4-查找" class="headerlink" title="4.查找"></a>4.查找</h5><p><strong>1.顺序表查找</strong></p>
<p><strong>二分法查找</strong>，low和high作为待元素的下界和上界，mid指示区间的中间位置。mid=(low+high)/2 向下取整，若mid对应的值大于被查找值key，则high = mid-1，否则low = mid+1，若相等则返回mid。当low&lt;=high时，返回未查找到。</p>
<p><strong>索引顺序表或分块查找</strong></p>
<p>将表分成几个子表，对每个子表建立一个索引项，包含关键字项（子表里面最大的数）和一个指针项。</p>
<p>索引表暗关键字有序，则表有序或块有序</p>
<p>所以最后的查找是分两步进行，先确定待查记录所在的块，然后在块里面顺序查找</p>
<p><strong>2.动态查找表</strong></p>
<p><strong>二叉排序树</strong></p>
<p>动态树表，若左子树不空，则左子树所有节点均小于根节点的值，同理，右子树的节点均大于根节点的值。若查找不成功，就将关键字插入查找路径的访问的最后一个节点的左孩子或右孩子中。</p>
<p>一个无序列表就可通过构造二叉排序树成为一个有序序列。</p>
<p><strong>3.哈希表</strong></p>
<p>使每一个关键字和结构中一个唯一的存储位置相对应。</p>
<p>哈希表有些<strong>构造方法</strong>，但注意不要产生同义词，产生冲突</p>
<p>1.直接定址法</p>
<p>2.数字分析法</p>
<p>3.平方取中法</p>
<p>4.折叠法</p>
<p>5.随机数法</p>
<p><strong>6.除留余数法</strong>    主流</p>
<p><strong>H(key) = key mod p</strong> ; p&lt;=m    m为表长</p>
<p>核心是对<strong>p</strong>的取值</p>
<p>一般经验：P可选为质数或不包含小于20的质因数的合数</p>
<p><strong>处理冲突的方法</strong></p>
<p><strong>1.开放定址法</strong></p>
<p>Hi = (H(key) + di) mod m    i = 1,2,3…,k  (k&lt;=m-1)    </p>
<p>H(key)为hash函数，m为hash表长，di为增量序列</p>
<p>di有三种取法</p>
<ol>
<li>线性探测再散列    di = 1,2,3….,m-1</li>
<li>二次探测再散列    di = 1,-1,4,-4,9,…,k^2    (k&lt;= m/2)</li>
<li>随机探测再散列    di = 随机数</li>
</ol>
<p><strong>2.再hash法</strong></p>
<p>Hi = RHi (key)</p>
<p>当产生冲突时计算另一个hash函数地址</p>
<p><strong>3.链地址法</strong>    主流</p>
<p>将所有关键字为同义词的记录存储在同一线性链表中，凡hash地址为i的记录都插入到线性链表中对应的头节点中，需保持同义词在同一线性链表中按关键字有序。</p>
<hr>
<p>对<strong>hash表的查找</strong>和hash表的构造过程基本一致</p>
<p>给定K值，根据构造表的hash函数求得hash地址，若表中此位置没有记录，则查找不成功，否则比较关键字，若相等，则查找成功</p>
<hr>
<h5 id="5-排序"><a href="#5-排序" class="headerlink" title="5.排序"></a>5.排序</h5><p>有两个基本操作，1.比较两个关键字的大小。    2.将记录从一个位置移到另一个位置。    一般改变存储方式避免2.</p>
<p><strong>1.插入排序</strong>    O(n^2)</p>
<p> 将一个记录插入到已排好序的有序表中，从而的到一个新的、记录值+1的有序表</p>
<p>也有一种折半插入排序，优化了查找，结合了之前的二分法查询，进行关键字的判断，进而得到位置    仍是O(n^2)</p>
<p><strong>2.希尔排序</strong></p>
<p>优化了时间复杂度</p>
<p>先将整个待排记录序列分割成若干个子序列分别进行直接插入排序，待记录基本有序之后，再对全体记录进行一次直接插入排序</p>
<p>特点是：子排序的构成不是简单的“逐段分割”，而是将<strong>相隔某个“增量”</strong>的记录组成的一个子序列。增量最好为质数，最后一次排序必须为1，通常为5,3,1</p>
<p><strong>3.快速排序</strong></p>
<p>1.起泡排序    O(n^2)</p>
<p>若为逆序（r[1.key&gt;r[2].key）交换两个记录的位置，然后比较第二个记录和第三个记录关键字，直至n-1和n进行比较过为止。</p>
<p>这算一次起泡排序，结果为最大的记录值被排到了最后一个的位置，之后进行第二次起泡排序，对前n-1个记录进行相同操作</p>
<p>2.快速排序</p>
<p>其是对起泡排序的一个改进</p>
<p><strong>核心思想</strong>为通过一次排序将待排记录分割成独立的两部分，其中一部分的关键字均比另一组的关键字小，则可分别对这两部分记录继续排序，以达到整个序列的有序</p>
<p>首先需要选取一个枢轴，一般为第一个记录，之后将比他小的记录移到左边，大的移到右边。这样的一次操作称作一次快排</p>
<p><strong>具体做法</strong>为附设两个指针low和high，初值指向low和high，还有一个枢轴记录的关键字pivotkey，之后首先从high的位置向前搜索找到第一个关键字小于pivotkey的记录并和枢轴记录交换位置，之后从low的位置向后搜索找到 一个比privotkey大的记录，并交换位置，重复这两部操作，直至low==high。<strong>可使用L[0]存储pivotkey</strong>，因为对枢轴的复制是多余的，只需要最后进行移位即可</p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="comment">//快速排序</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">Prtition</span><span class="params">(SqList &amp;L,<span class="keyword">int</span> low,<span class="keyword">int</span> high)</span></span>&#123;</span><br><span class="line">    L.r[<span class="number">0</span>] = L.r[low];	<span class="comment">//子表的第一个记录做枢轴记录</span></span><br><span class="line">    privotkey = L.r[low].key;</span><br><span class="line">    <span class="keyword">while</span>(low&lt;high)&#123;	<span class="comment">//从表的两端交替向中间扫描</span></span><br><span class="line">        <span class="keyword">while</span>(low&lt;high &amp;&amp; L.r[high].key&gt;=privotkey)	--high;</span><br><span class="line">            L.r[low] = L.r[high];	<span class="comment">//比枢轴记录小的记录移到左边</span></span><br><span class="line">        <span class="keyword">while</span>(low&lt;high &amp;&amp; L.r[low].key&gt;=privotkey)	++low;</span><br><span class="line">            L.r[high]  = L.r[low];<span class="comment">//比枢轴记录大的记录移到右边</span></span><br><span class="line">    &#125;</span><br><span class="line">    L.r[low] = L.r[<span class="number">0</span>];	<span class="comment">//枢轴记录到位</span></span><br><span class="line">    <span class="keyword">return</span> low;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.<strong>选择排序</strong></p>
<p>1.简单选择排序</p>
<p>通过n-i次关键字比较，选出最小的一个记录，并和第i个记录交换</p>
<p>2.树形选择排序</p>
<p>首先n个关键字进行两两比较，然后再n/2(向上取整)个较小者之间再两两比较，如此重复，直至选出最小的关键字为止</p>
<p>可使用有n个叶子节点的完全二叉树表示，两两比较，最后的<strong>根</strong>即是最小，之后选出次最小关键字，只需<strong>将原来的叶子节点里面的最小关键字，即上一次选出来的根的那个关键字，变为无穷大</strong>，这样就选出了次最小关键字</p>
<p>3.堆排序</p>
<p>堆排序是对树形选择排序的优化，主要是“筛选”，“建堆”</p>
<p>4归并排序</p>
<p>将两个或以上的有序表组合成一个新的有序表</p>
<hr>
<h4 id="3-计算机算法思想"><a href="#3-计算机算法思想" class="headerlink" title="3.计算机算法思想"></a>3.计算机算法思想</h4><h5 id="1-递归与分治"><a href="#1-递归与分治" class="headerlink" title="1.递归与分治"></a>1.递归与分治</h5><p>递归看之前的一些就行，这里主要说分治法，各个击破，分而治之</p>
<p>基本思想是将一个规模为n的问题分解成k个规模较小的子问题，这些子问题相互独立，不包含公共的子问题，且与原问题相同，递归的解这些子问题（将这些子问题继续划分），然后将各个子问题的解合并得到原问题的解。常见的 k = 2</p>
<p>例：二分查找技术，棋盘覆盖，归并排序，快速排序等的具体实现</p>
<h5 id="2-动态规划"><a href="#2-动态规划" class="headerlink" title="2.动态规划"></a>2.动态规划</h5><p>适用于解最优化问题，依赖于问题本身的两个核心性质：最优子结构性质和子问题重叠性质。分解的子问题往往不是互相独立的</p>
<p>最优子结构性质：动态规划算法的第一步首先是构造最优解的结构，当问题的最优解包含了其子问题的最优解，称为最优子结构</p>
<p>重叠子问题：递归运算自顶向下解此问题时，每次产生的子问题并不总是新问题，有些种子问题被计算多次，动态规划利用此性质，对每个子问题只解一次，而后将其解保存在一个表格中，当需要再次解此子问题时，只需要查看一下表格。</p>
<p>其每一步的选择都依赖于相关子问题的解，只有相关子问题的解出来后，才进行选择</p>
<ol>
<li>找出最优解的性质，并刻画其结构特征</li>
<li>递归的定义最优值</li>
<li>以自底向上的方式计算出最优值</li>
<li>根据计算最优值时得到的信息，构造最优解</li>
<li>定义动态规划式，给出动态规划递归式，给出非递归代码</li>
</ol>
<p>例：矩阵连乘，最长公共子序列，最大子段和（分治与动规的区分），租用游艇问题</p>
<p>分治和动规都是自底向上解决问题</p>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="comment">//租用游艇问题</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getMinRent</span><span class="params">(<span class="keyword">int</span> n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">int</span> dp[<span class="number">200</span>];<span class="comment">//令dp[i]为从出租站1到出租站n所需要的最少租金 </span></span><br><span class="line">	dp[<span class="number">1</span>]=<span class="number">0</span>;<span class="comment">//初始化 </span></span><br><span class="line">	dp[<span class="number">2</span>]=r[<span class="number">1</span>][<span class="number">2</span>];<span class="comment">//初始化 </span></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">3</span>;i&lt;=n;i++)</span><br><span class="line">	&#123;</span><br><span class="line">		dp[i]=r[<span class="number">1</span>][i];<span class="comment">//先初始化dp[i]为第1到i站的租金 </span></span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">2</span>;j&lt;i;j++)</span><br><span class="line">		&#123;</span><br><span class="line">			dp[i]=min(dp[i],dp[j]+r[j][i]);<span class="comment">//状态转移方程 </span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> dp[n];<span class="comment">//返回n个 </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h5 id="3-贪心算法"><a href="#3-贪心算法" class="headerlink" title="3.贪心算法"></a>3.贪心算法</h5><p>并不从整体最优上进行考虑，而是在局部最优进行选择，我们希望最后的结果也是整体最优的，虽然一些时候并不知道最优解，但最终结果确实最优解的很好地近似解。通常自顶向下进行求解</p>
<p>贪心每次仅做局部最优解，之后去解做出这个选择后产生的相应的子问题。</p>
<p>贪心算法基本要素：最优子结构性质，</p>
<p>贪心选择性质：所求问题的整体最优解可通过一系列局部最优的选择来达到。而且需要证明每一步做的贪心选择最终导致问题的整体最优解</p>
<p>例：活动安排问题，最优装载，多机调度问题，dijkstra最短路径算法，最小生成树算法</p>
<hr>
<h5 id="4-回溯法"><a href="#4-回溯法" class="headerlink" title="4.回溯法"></a>4.回溯法</h5><p>深度遍历解空间树，从根节点进行遍历，当发现某一节点肯定不包含问题的解，则跳过对其子树的遍历，逐层向祖先节点回溯</p>
<p>通常解题步骤为：首先定义问题的解空间树；确定易于搜索的解空间结构；深度优先搜索解空间，并在搜索过程中使用剪枝函数避免无效搜索</p>
<p>通常使用剪枝函数避免无效搜索：</p>
<p>1.用约束函数咋扩展节点处剪去不满足约束的子树</p>
<p>2.用限界函数减去得不到最优解的子树</p>
<p>一般可使用递归回溯，迭代回溯，子集树与排列树</p>
<p>子集树：从n个元素中找出满足要求的子集</p>
<p>排列树：确定n个元素满足某种性质的排列</p>
<img src="https://img-blog.csdnimg.cn/20200702193813843.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0NzY2ODgz,size_16,color_FFFFFF,t_70" alt="图" style="zoom: 50%;" />

<p>例：0-1背包问题，旅行售货员问题 ，装载问题</p>
<hr>
<h5 id="5-分支限界法"><a href="#5-分支限界法" class="headerlink" title="5.分支限界法"></a>5.分支限界法</h5><p>广度优先+剪枝</p>
<p>一般来说，回溯法是求出问题的所有解；分支限界是求出一个解，或者说是在满足某一约束的最优解</p>
<p>在分支限界法中，活节点一旦成为扩展节点，就一次性生成所有子节点，舍弃所有不可行解或非最优解的儿子节点，其余儿子节点加入活结点表中。</p>
<p>从活节点表中选择下一扩展节点有几种方式</p>
<p>1.先入先出方式</p>
<p>2.优先队列式分支限界法（看哪一个节点先成为扩展节点）</p>
<p>例：装载问题，旅行员售货问题</p>
<p>总之先写到这里了，后面再改吧</p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">晟松</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://chengsong.info/2020/09/17/数据结构和算法/">https://chengsong.info/2020/09/17/数据结构和算法/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://chengsong.info">晟松</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E7%AE%97%E6%B3%95/">算法</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2020/09/30/js%E5%90%84%E7%A7%8D%E7%9F%A5%E8%AF%86/"><i class="fa fa-chevron-left">  </i><span>js各种知识</span></a></div><div class="next-post pull-right"><a href="/2020/09/10/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%9F%BA%E7%A1%80/"><span>计算机网络基础</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer class="footer-bg" style="background-image: url(/img/blog-bg.jpg)"><div class="layout" id="footer"><div class="copyright">&copy;2020 - 2023 By 晟松</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="icp"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><span>湘ICP备2020021729号</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>